package com.zhang.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhang.common.lang.Result;
import com.zhang.entity.VisitCount;
import com.zhang.service.VisitCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 张立松
 * @since 2023-05-09
 */
@RestController
@RequestMapping("/visit")
public class VisitCountController {

    @Autowired
    VisitCountService visitCountService;

    @GetMapping("/count")
    public Result getWholeCount(){
        Integer day = 0;
        Integer week = 0;
        Integer month = 0;
        Integer total = 0;
        Integer temp;
        List<VisitCount> visitCounts = visitCountService.list(null);
        for(VisitCount v : visitCounts){
            temp = v.getCount()+v.getRandom();
            total += temp;
            if(v.getDate().isAfter(LocalDate.now().minusDays(30L))){
                month += temp;
                if(v.getDate().isAfter(LocalDate.now().minusDays(7L))){
                    week += temp;
                    if(v.getDate().isEqual(LocalDate.now())){
                        day += temp;
                    }
                }
            }
        }
        return Result.success(MapUtil.builder()
                .put("day",day).put("week",week).put("month",month).put("total",total).map());
    }

    @GetMapping("/daysCount/{days}")
    public Result getSevenDayCount(@PathVariable("days")Long days){

        LocalDate daysAgo = LocalDate.now().minusDays(days);
        List<VisitCount> visitCounts = visitCountService
                .list(new QueryWrapper<VisitCount>().gt("date", daysAgo).orderByAsc("date"));
        if(visitCounts.size()==0){
            return Result.success(null);
        }
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();
        for (VisitCount v : visitCounts){
            dateList.add(v.getDate());
            countList.add(v.getCount()+v.getRandom());
        }

        return Result.success(MapUtil.builder().put("date",dateList).put("count",countList).map());
    }

}

